package cac.fenjian.resource.msBulkyItems.service;

import cac.common.CallInterFace.service.CallInterfaceService;
import cac.common.CreatMsgId;
import cac.fenjian.resource.DirectDelivery.dao.DirectDeliveryDao;
import cac.fenjian.resource.DirectDelivery.service.DirectDeliveryService;
import cac.fenjian.resource.msBulkyItems.dao.MsBulkyItemsDao;
import cac.gkinterface.service.WorkService;
import com.alibaba.fastjson.JSONObject;
import com.cac.dme.adapter.rest.msg.QueryReqBean;
import com.cac.dme.adapter.rest.msg.QueryRespBean;
import com.cac.dme.adapter.utils.ComUtil;
import com.cac.dme.adapter.utils.PageHelper;
import com.cac.dme.common.exception.service.DaoException;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class MsBulkyItemsService {
    @Autowired
    private MsBulkyItemsDao msBulkyItemsDao;
    @Autowired
    private DirectDeliveryDao directDeliveryDao;
    @Autowired
    private CallInterfaceService callInterfaceService;
    @Autowired
    private WorkService workService;

    /*大件货物明细查询*/
    @Transactional
    public QueryRespBean<HashMap> msBulkyItemsSearch(QueryReqBean<HashMap> queryReqBean, String orderBy, String Keywords) {
        QueryRespBean<HashMap> queryRespBean = new QueryRespBean<>();
        try {
            PageHelper.startPage(queryReqBean.getPageParameter());
            HashMap searchParams = queryReqBean.getSearchParams();
            Page<HashMap> dataList = msBulkyItemsDao.msBulkyItemsSearch(searchParams, orderBy, Keywords);
            queryRespBean.setResult(dataList);
            return queryRespBean;
        } catch (Exception e) {
            throw new DaoException(e.getMessage(), e);
        }
    }

    /*判断查询是否为空*/
    @Transactional
    public List<HashMap> msBulkyItemsSearch(HashMap searchParams, String orderBy, String Keywords) {
        try {
            Page<HashMap> dataList = msBulkyItemsDao.msBulkyItemsSearch(searchParams, orderBy, Keywords);
            return dataList;
        } catch (Exception e) {
            throw new DaoException(e.getMessage(), e);
        }
    }

    /*大件货物明细新增*/
    @Transactional
    public int msBulkyItemsInsert(Map map) {
        try {
            int count = msBulkyItemsDao.msBulkyItemsInsert(map);
            return count;
        } catch (Exception e) {
            throw new DaoException(e.getMessage(), e);
        }
    }

    /*大件货物明细修改*/
    @Transactional
    public int msBulkyItemsUpdate(Map map) {
        try {
            int count = msBulkyItemsDao.msBulkyItemsUpdate(map);
            if (count == 0) {
                throw new DaoException("修改数据失败");
            }
            return count;
        } catch (Exception e) {
            throw new DaoException(e.getMessage(), e);
        }
    }

    /*大件货物明细删除*/
    @Transactional
    public int msBulkyItemsDelete(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new DaoException("删除失败！传入的参数主键为null");
        }
        try {
            //记录日志
            HashMap hashmap = msBulkyItemsDao.msBulkyItemsFindId(id);
            if (hashmap == null) {
                throw new DaoException("删除失败！对象不存在");
            }
//删除业务数据
            int count = msBulkyItemsDao.msBulkyItemsDelete(id);
            return count;
        } catch (Exception e) {
            throw new DaoException(e.getMessage(), e);
        }
    }

    //2023-07-18 库存大件不能参与分拣无法装上托盘的货物自动生成占用信息
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void bulkySortedAuto(String packageId) {
        //通过工作包id寻找次工作包下所有配套完成的大件，
        List<HashMap> bulkyItems = msBulkyItemsDao.searchBulkyItemAbleSort(packageId);
        try {
            if (Objects.isNull(bulkyItems)) {
                return;
            } else {
                for (HashMap data : bulkyItems) {
                    //修改matchinfo
                    msBulkyItemsDao.updateMatchInfo(data);
                    //修改台账占用
                    msBulkyItemsDao.updateItemInventory(data);
                    //创建占用信息
                    String allotId = ComUtil.getId();
                    data.put("wmsInvOutAllotmentId", allotId);
                    this.allBData(data);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException();
        }

    }

    @Async
    //接收直配方法上传分拣占用
    public void allBData(HashMap map) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        JSONObject headersMap = new JSONObject();
        String msgId = CreatMsgId.getMsgId();
        HashMap param = new HashMap();
        //获取func
        headersMap.put("func", "101-ERP-sortingAllot");
        headersMap.put("msgId", msgId);
        //查询占用id
        String id = directDeliveryDao.searchAllotId(map);
        //分拣占用接口所需参数
        param.put("opUserCode", "488831");
        param.put("originalId", id);
        param.put("wmsItemInventoryId", map.get("WMS_ITEM_INVENTORY_ID").toString());
        param.put("productCode", map.get("PRODUCT_CODE").toString());
        param.put("batchNo", map.get("BATCH_NO").toString());
        param.put("startLotNo", map.get("START_PLANE_NO").toString());
        param.put("endLotNo", map.get("START_PLANE_NO").toString());
        param.put("applyQty", map.get("DELIVERY_QTY").toString());
        param.put("allotmentQty", map.get("DELIVERY_QTY").toString());
        param.put("aoNo", map.get("AO_CODE").toString());
        param.put("userIp", "172.17.101.150");
        param.put("taskNo", " ");
        param.put("recHrDeptId", " ");
        //装换为json格式
        JSONObject data = new JSONObject(param);
        headersMap.put("data", data);
        String headersmap = headersMap.toJSONString();
        //对已经转换成字符串的数据进行加密
        final Base64.Encoder encoder = Base64.getEncoder();
        String parameters = encoder.encodeToString(headersmap.getBytes());
        String code = "sendBData";
        String sendScenario = "分拣占用";
        String name = "两网传输-发送业务数据";
        callInterfaceService.sendBData(code, name, parameters, sendScenario);

        //工控网上传数据
        HashMap issuedTest = new HashMap();
        issuedTest.put("BData", headersmap);
        issuedTest.put("msgId", msgId);
        issuedTest.put("type", headersMap.get("func"));
        workService.issuedTest(issuedTest);
    }

    public int searchItemCode(HashMap map){
        return msBulkyItemsDao.searchItemCode(map);
    }
}
